package com.hs.rabbitmqdemo;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.boot.autoconfigure.amqp.RabbitProperties;
import org.springframework.boot.autoconfigure.amqp.RabbitProperties.*;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @ClassName MyListener
 * @Description TODO RabbitMQ 的监听器
 * @Author 郭敖
 * @Date 2023年09月27日 19:12
 * @Version 1.0
 */
@Component
public class MyListener {
    @RabbitListener(    queues = "item_queue")
    public void myListener1(String message){
        System.out.println("接收的消息为："+message);
    }

    @RabbitListener(queues = "fanout1")
    public void fanoutListener1(String message){
        System.out.println("fanout1的消息是:"+message);
    }
    @RabbitListener(queues = "fanout2")
    public void fanoutListener2(String message, Message mes, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) Long deliveryTag) throws IOException {
        System.out.println("fanout2的消息是:"+message);
        System.out.println("fanout2的message是"+mes);
        System.out.println("fanout的deliverTag是"+deliveryTag);
        System.out.println();
        //手动签收
        try {
            // 第二个参数是否为批量确认
            channel.basicAck(mes.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            /*
             * 第一个参数：deliveryTag，该消息的index
             * 中间参数：是否批量处理
             * 最后一个参数：requeue，被拒绝的是否重新入队列(true重发)
             * channel.basicNack 与 channel.basicReject 的区别在于basicNack可以拒绝多条消息，而basicReject一次只能拒绝一条消息
             */
            channel.basicNack(mes.getMessageProperties().getDeliveryTag(),true,true);
        }
    }
}
